/**
 * 主题状态管理
 */
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export type Theme = 'light' | 'dark' | 'system'

interface ThemeState {
  theme: Theme
  setTheme: (theme: Theme) => void
  getEffectiveTheme: () => 'light' | 'dark'
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      theme: 'system',
      setTheme: (theme: Theme) => {
        set({ theme })
        applyTheme(theme)
      },
      getEffectiveTheme: () => {
        const { theme } = get()
        if (theme === 'system') {
          return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
        }
        return theme
      },
    }),
    {
      name: 'theme-storage',
    }
  )
)

// 应用主题
function applyTheme(theme: Theme) {
  const root = document.documentElement
  const effectiveTheme = theme === 'system'
    ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
    : theme

  root.classList.remove('light', 'dark')
  root.classList.add(effectiveTheme)
  
  // 保存到 localStorage
  localStorage.setItem('theme', effectiveTheme)
}

// 初始化主题
export function initTheme() {
  const store = useThemeStore.getState()
  applyTheme(store.theme)

  // 监听系统主题变化
  if (store.theme === 'system') {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      applyTheme('system')
    })
  }
}

